#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/6/15 14:30
# @Author  : fuchen'en
# @Description:
import pika
import sys

credentials = pika.PlainCredentials('test', 'test123')
parameters = pika.ConnectionParameters(host='10.0.20.66',
                                       port='5672',
                                       virtual_host='/',
                                       credentials=credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()

# 采用直连模式接收消息
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
print(queue_name)

severities = sys.argv[1:]
if not severities:
    sys.stderr.write("Usage: {!s} [info] [warning] [error]\n".format(sys.argv[0]))
    sys.exit(1)

# 给每一种日志类型都绑定一个key，并且一个队列可以绑定多个key（路由key）
# 交换机会根据路由key来进行选择性转发对应消息
print(severities)
for severity in severities:
    channel.queue_bind(queue=queue_name, exchange='direct_logs', routing_key=severity)

print(' [*] Waiting for logs. To exit Press CTRL + C')


def callback(ch, method, properties, body):
    print(' [x] {!r}:{!r}'.format(method.routing_key, body))


channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)

channel.start_consuming()
